package com.ld.poetry.utils;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 *  请求工具类
 * created by vital on 2024/10/7 下午12:26
 */
@Slf4j
public class RequestUtils {

    private static final String UNKNOWN = "unknown";

    /**
     * 获取真实ip地址
     * @param request 请求对象
     * @return ip地址
     */
    public static String getRealIp(HttpServletRequest request){
        if (request == null) {
            return null;
        }
        // 尝试从请求头中获取客户端IP
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_FORWARDED",
                "HTTP_X_CLUSTER_CLIENT_IP",
                "HTTP_CLIENT_IP",
                "HTTP_FORWARDED_FOR",
                "HTTP_FORWARDED",
                "HTTP_VIA",
                "REMOTE_ADDR"
        };

        // 遍历所有可能的头
        for (String header : headers) {
            String ip = request.getHeader(header);
            if (ip != null && !ip.isEmpty() && !UNKNOWN.equalsIgnoreCase(ip)) {
                log.debug("{}: {}", header, ip);
                // 处理多IP的情况
                int commaIndex = ip.indexOf(',');
                if (commaIndex > 0) {
                    ip = ip.substring(0, commaIndex);
                }
                // 返回第一个IP
                log.info("Real IP: {}", ip);
                return ip;
            }
        }

        // 如果所有头部都无效，则返回远程地址
        String remoteAddr = request.getRemoteAddr();
        log.info("REMOTE_ADDR: {}", remoteAddr);
        return remoteAddr;
    }

    /**
     * 获取真实访问地址
     * @param request
     * @return
     */
    public static String getRealRoute(HttpServletRequest request){

        String forwardedHost = request.getHeader("X-Forwarded-Host");
        String forwardedProto = request.getHeader("X-Forwarded-Proto");
        if (forwardedHost != null && forwardedProto != null) {
            return forwardedProto + "://" + forwardedHost;
        }

        //获取访问域名
        StringBuffer url = request.getRequestURL();
        String rootUrl = url.substring(0, url.indexOf("/", 8));
        System.out.println(rootUrl);
        return rootUrl;
    }


}
